package com.example.signtime.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.bean.ApiResult;
import com.example.signtime.mapper.SignTimeMapper;
import com.example.signtime.modules.entity.SignTime;
import com.example.signtime.modules.vo.SignRecordsVO;
import com.example.signtime.service.SignTimeService;
import com.example.util.DateUtils;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.util.*;

@Service
public class SignTimeServiceImpl extends ServiceImpl<SignTimeMapper, SignTime> implements SignTimeService {

   @Autowired
    private SignTimeMapper signTimeMapper;
    @Override
    public String signIn(Integer userId) {
        //判断当天的某个时间段是否已经签到过
        Date time = new Date();
        int timePerods = timePerods(time);
        QueryWrapper<SignTime> qw = new QueryWrapper<>();
        qw.eq("user_id",userId).last(" and date(sign_in_time) =  date(CURRENT_DATE)");
        SignTime sign = getOne(qw);
        if (Objects.nonNull(sign)){
            return "一天内不能重复打卡";
        }
        SignTime signTime = new SignTime();
        signTime.setUserId(userId);
        signTime.setSignInTime(time);
        signTime.setPeriods(timePerods);
        save(signTime);
        return "打卡成功";
    }

    @Override
    public ApiResult getSign(Integer id) {
        return ApiResult.success(getById(id));
    }

    @Override
    public ApiResult getSignList(Integer countDays) {
        return ApiResult.success(signTimeMapper.getSignList(countDays));
    }

    @Override
    public SignRecordsVO getSignRecord(Integer userId) {
        SignRecordsVO signRecord = new SignRecordsVO();
        Integer signRecordTotals = signTimeMapper.getSignRecord(userId);
        signRecord.setSignRecordTotals(signRecordTotals);
        List<Date> dates = signTimeMapper.signDates(userId);
        //使用TreeMap排序，获取一周的日期，格式为MM-dd
        long distanceDay = DateUtils.getDistanceDay(DateUtils.getCurrMonthFirst(), DateUtils.getCurrMonthLast());
        Map<String,Boolean> map = new TreeMap<>();
        for (int i = 0; i <= (int) distanceDay; i++) {
            map.put(DateUtils.formatDate(org.apache.commons.lang3.time.DateUtils.addDays(DateUtils.getCurrMonthFirst(),i),
                    "MM-dd"),false);
        }

        dates.forEach(item->{
            map.put(DateUtils.formatDate(item,"MM-dd"),true);
        });

//        List<Boolean> weekRecords = Lists.newArrayList(map.values());
//        List<String> months = Lists.newArrayList(map.keySet());
//        signRecord.setWeekRecords(weekRecords);
//        signRecord.setMonths(months);
        signRecord.setMonthMap(map);
        //统计连续打卡天数
        signRecord.setContinuousDay(persistentDay(dates));
        //统计打卡排名
//        List<Integer> sortRecordList = Lists.newArrayList();
//        QueryWrapper<SignTime> qw = new QueryWrapper<>();
//        qw.groupBy("user_id");
//        list(qw).forEach(item->{
//            sortRecordList.add(signTimeMapper.getSignRecord(item.getUserId()));
//        });
//        sortRecordList.sort(new Comparator<Integer>() {
//            @Override
//            public int compare(Integer o1, Integer o2) {  //反序排序
//                return o2 - o1;
//            }
//        });
//        signRecord.setSortRecordList(sortRecordList);
//        signRecord.setSortRecord(sortRecordList.indexOf(signRecordTotals) + 1);
        return signRecord;
    }

    /**
     * 统计出最大连续打卡天数
     * @param signInDates
     * @return
     */
    private static int persistentDay(List<Date> signInDates) {
        if (signInDates.size() == 0){
            return 0;
        }
        //对日期进行从小到大的排序
        List<Date> sortDates = Lists.newArrayList(new TreeSet<>(signInDates));
        //定义一个变量表示连续签到天数，从1开始
        int continuousDay = 1;
        int maxContinuousDay = 1;
        for (int i = 0; i < sortDates.size() - 1; i++) {
            long intervalDay = DateUtils.getDistanceDay(sortDates.get(i),sortDates.get(i + 1));
            if (intervalDay == 1){
                continuousDay++;
            }else{
                maxContinuousDay = maxContinuousDay <= continuousDay ? continuousDay : maxContinuousDay;
                continuousDay = 1;
            }
        }
        maxContinuousDay = maxContinuousDay <= continuousDay ? continuousDay : maxContinuousDay;
        return maxContinuousDay;
    }


    /**
     * 返回判断当前时间是早、下、晚、凌晨的哪个时间段。
     * @return
     */
    private int timePerods(Date time){
        long mT = 0l;
        long zT = 0l;
        long eT = 0l;
        long dT = 0l;
        long tm = 0l;
        try {
            mT = DateUtils.parseDate("06:00:00", "HH:mm:ss").getTime();
            zT = DateUtils.parseDate("12:00:00", "HH:mm:ss").getTime();
            eT = DateUtils.parseDate("18:00:00", "HH:mm:ss").getTime();
            dT = DateUtils.parseDate("24:00:00", "HH:mm:ss").getTime();
            tm = DateUtils.parseDate(DateUtils.formatDate(time,"HH:mm:ss"),"HH:mm:ss").getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (tm >= mT && tm < zT){  //早上
            return 0;
        }else if (tm >= zT && tm < eT){ //下午
            return 1;
        }else if (tm >= eT && tm < dT){  //晚上
            return 2;
        }else {  //凌晨
            return 3;
        }
    }
}
